package com.Cfeng.XiaohuanChat;

import com.Cfeng.XiaohuanChat.entity.ChatMessage;
import com.Cfeng.XiaohuanChat.repository.ChatMessageRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * @author Cfeng
 * @date 2022/8/14
 */

@SpringBootTest
public class MongoDBtest {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private ChatMessageRepository messageRepository;

    @Test
    public void testMongo() {
        Query query = new Query();
        Criteria criteria = new Criteria().orOperator(Criteria.where("receiver").is(null),Criteria.where("receiver").is(""));
        query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC,"createTime")).limit(10);
        List<ChatMessage> result = mongoTemplate.find(query,ChatMessage.class);
        //使用sort，选择Comparator排序器的comparing方法选择参数进行比较
        result.sort(Comparator.comparing(ChatMessage::getCreateTime));
        System.out.println(result);
    }

    @Test
    public void testMongoRepository() {
        List<ChatMessage> result = messageRepository.findTop10ByReceiverIsNullOrderByCreateTimeDesc();
        System.out.println(result);
    }
}
